package com.itmk.utils;


import com.itmk.config.qiniu.QiNiuConfig;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import lombok.Data;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 七牛云上传文件工具类
 */

@Data
@Component
public class QiniuCloudUtil {
    private QiNiuConfig qiNiuConfig;
    private Auth auth;
    @Autowired
    public QiniuCloudUtil(QiNiuConfig qiNiuConfig) {
        this.qiNiuConfig = qiNiuConfig;
        this.auth= Auth.create(qiNiuConfig.getAccesskey(),qiNiuConfig.getSecretkey());
    }

    public QiniuCloudUtil() {
    }
    //     密钥



    public  String getUpToken() {
        return auth.uploadToken(qiNiuConfig.getBucketname(), null, qiNiuConfig.getExpiration(), new StringMap().put("insertOnly", 1));
    }

    //base64方式上传
    public  String put64image(byte[] base64, String key) throws Exception {
        String file64 = Base64.encodeToString(base64, 0);
        Integer len = base64.length;

        //华北空间使用 upload-z1.qiniu.com，华南空间使用 upload-z2.qiniu.com，北美空间使用 upload-na0.qiniu.com
        String url = "http://upload-z2.qiniu.com/putb64/" + len + "/key/" + UrlSafeBase64.encodeToString(key);

        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);
        //返回图片地址   https://q5jhgxz4q.bkt.clouddn.com/812bbd78-62d3-44bc-836c-9ee27ba4866a
        //用此地址可在网页中访问到上传的图片
        return qiNiuConfig.getDomain() + "/"+key;
    }

    /**
     * @param key 图片的文件名
     * @Explain 删除空间中的图片
     */
    public Boolean delete(String key) {
        Configuration configuration=new Configuration(Region.region0());
        BucketManager bucketManager = new BucketManager(auth,configuration);
        try {
            bucketManager.delete(qiNiuConfig.getBucketname(), key);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

